Page({
  data: {
    messages: [],
    inputValue: '',
    unreadCount: 1,
    sessionId: 'session001'
  },

  onLoad() {
    this.loadMessages()
    this.scrollToBottom()
  },

  onShow() {
    this.loadMessages()
  },

  loadMessages() {
    // 从本地存储加载消息
    const messages = wx.getStorageSync(`messages_${this.data.sessionId}`) || this.getMockMessages()
    
    this.setData({
      messages: messages.map(msg => ({
        ...msg,
        formattedTime: this.formatTime(msg.time)
      }))
    })
    
    // 延迟滚动到底部
    setTimeout(() => {
      this.scrollToBottom()
    }, 100)
  },

  getMockMessages() {
    return [
      {
        id: 1,
        type: 'system',
        content: '您好，欢迎咨询智云旅游客服，有什么可以帮助您的吗？',
        time: new Date(Date.now() - 30 * 60 * 1000).toISOString()
      },
      {
        id: 2,
        type: 'user',
        content: '我想了解一下订单退款流程',
        time: new Date(Date.now() - 25 * 60 * 1000).toISOString()
      },
      {
        id: 3,
        type: 'service',
        content: '好的，退款流程如下：\n1. 进入订单详情页\n2. 点击"申请退款"按钮\n3. 填写退款原因并提交\n4. 等待审核，一般3-5个工作日处理完成',
        time: new Date(Date.now() - 20 * 60 * 1000).toISOString()
      },
      {
        id: 4,
        type: 'user',
        content: '好的，谢谢',
        time: new Date(Date.now() - 15 * 60 * 1000).toISOString()
      },
      {
        id: 5,
        type: 'service',
        content: '不客气，如果还有其他问题，随时可以咨询我。',
        time: new Date(Date.now() - 10 * 60 * 1000).toISOString()
      }
    ]
  },

  formatTime(timeStr) {
    const date = new Date(timeStr)
    const now = new Date()
    const diff = now - date
    
    if (diff < 60000) {
      return '刚刚'
    } else if (diff < 3600000) {
      return `${Math.floor(diff / 60000)}分钟前`
    } else if (diff < 86400000) {
      return `${Math.floor(diff / 3600000)}小时前`
    } else {
      const month = date.getMonth() + 1
      const day = date.getDate()
      const hours = String(date.getHours()).padStart(2, '0')
      const minutes = String(date.getMinutes()).padStart(2, '0')
      return `${month}月${day}日 ${hours}:${minutes}`
    }
  },

  onInput(e) {
    this.setData({
      inputValue: e.detail.value
    })
  },

  sendMessage() {
    const content = this.data.inputValue.trim()
    if (!content) {
      return
    }

    const newMessage = {
      id: Date.now(),
      type: 'user',
      content: content,
      time: new Date().toISOString()
    }

    const messages = [...this.data.messages, newMessage]
    this.setData({
      messages: messages.map(msg => ({
        ...msg,
        formattedTime: this.formatTime(msg.time)
      })),
      inputValue: ''
    })

    // 保存到本地存储
    wx.setStorageSync(`messages_${this.data.sessionId}`, messages)

    // 滚动到底部
    setTimeout(() => {
      this.scrollToBottom()
    }, 100)

    // 模拟客服回复（实际项目中通过WebSocket接收）
    setTimeout(() => {
      this.receiveServiceMessage()
    }, 2000)
  },

  receiveServiceMessage() {
    const serviceMessage = {
      id: Date.now(),
      type: 'service',
      content: '收到您的消息，客服正在为您处理...',
      time: new Date().toISOString()
    }

    const messages = [...this.data.messages, serviceMessage]
    this.setData({
      messages: messages.map(msg => ({
        ...msg,
        formattedTime: this.formatTime(msg.time)
      }))
    })

    wx.setStorageSync(`messages_${this.data.sessionId}`, messages)

    setTimeout(() => {
      this.scrollToBottom()
    }, 100)
  },

  scrollToBottom() {
    wx.createSelectorQuery().select('#message-list').boundingClientRect((rect) => {
      if (rect) {
        wx.pageScrollTo({
          scrollTop: rect.height + 1000,
          duration: 300
        })
      }
    }).exec()
  },

  goBack() {
    wx.navigateBack()
  }
})

